#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/stat.h>
#include <fcntl.h>

#define SIZE 1024 
#define MAX_ARGV 64
#define SEP " "
#define STREND '\0'
//1用户名
//2主机名
//3当前路径

//下面都和重定向有关
#define NoneRedir -1
#define StdinRedir 0
#define StdoutRedir 1
#define AppendRedir 2

#define IgnSpace(buf,pos) do {while(isspace(buf[pos])) pos++;}while(0)

int redir_type = NoneRedir;
char* filename = NULL;


char* argv[MAX_ARGV];
char pwd[SIZE];
char env[SIZE];//for test
int lastcode = 0;
// ls -a -l > log.txt


char* GetEnv(int a)
{
    if(a == 1)
    {
        char* username = getenv("USER");
        if(username == NULL) username = "NONE";
        return username;
    }

    if(a == 2)
    {
        char* hostname = getenv("HOSTNAME");
        if(hostname == NULL) hostname = "NONE";
        return hostname;
    }

    if(a == 3)
    {
        char* pwd = getenv("PWD");
        if(pwd == NULL) pwd = "NONE";
        return pwd; 
    }

}

char* Home()
{
    return getenv("HOME");
}

int Internative(char out[],int size)
{

    //输入提示符并获取用户输入的命令字符串"ls -a -l"
    printf("[%s@%s %s]$ ",GetEnv(1),GetEnv(2),GetEnv(3));

    fgets(out,size,stdin);//fgets会敲回车，所以多了个空行，把空行去掉
    out[strlen(out)-1] = 0;
    return strlen(out);
//    printf("test:%s\n",out); 
}


void CheckRedir(char in[])
{
    redir_type = NoneRedir;
    filename = NULL;
    int pos = strlen(in)-1;

    while(pos>=0)
    {
        if(in[pos] == '>')
        {
            if(in[pos-1] == '>')
            {
                redir_type = AppendRedir;
                in[pos-1] = STREND;
                pos++;
                IgnSpace(in,pos);
                filename = in+pos;
                break;
            }
            else
            {
                redir_type = StdoutRedir;
                in[pos++] = STREND;
                IgnSpace(in,pos);
                filename = in+pos;
                break;
            }
        }
        else if(in[pos] == '<')
        {
            redir_type = StdinRedir;
            in[pos++] = STREND;
            IgnSpace(in,pos);
            filename = in+pos;
            break;
        }
        else pos--;
    }
}

void Split(char in[])
{
    //ls -a -l > log.txt
    CheckRedir(in);
    int i = 0;
    argv[i++] = strtok(in,SEP);
    while(argv[i++] = strtok(NULL,SEP));
    if(strcmp("ls",argv[0]) == 0)
    {
        argv[i-1]=(char*)"--color";
        argv[i]=NULL;
    }
}


void Execute()
{

    pid_t id = fork();
    if(id == 0)
    {
        int fd = -1;
        if(redir_type == StdinRedir)
        {
            fd = open(filename,O_RDONLY);
            dup2(fd,0);
        }

        else if(redir_type == StdoutRedir)
        {
            fd = open(filename,O_WRONLY | O_CREAT | O_TRUNC,0666);
            dup2(fd,1);
        }
        else if(redir_type == AppendRedir)
        {
            fd = open(filename,O_WRONLY | O_CREAT | O_APPEND,0666);
            dup2(fd,1);
        }
        else {};

        //让子进程执行命令
        execvp(argv[0],argv);
        exit(1);
    }
   
    int status = 0;
    pid_t rid = waitpid(id,&status,0);
    if(rid == id) lastcode = WEXITSTATUS(status);
    //printf("run done ,rid:%d\n",rid);
}

int BuildinCmd()
{
    int ret = 0;
    //1.检测是否是内建命令，1/0
    if(strcmp("cd",argv[0]) == 0)
    {
        ret = 1;
        char* target = argv[1];
        if(!target) target=Home();

        chdir(target);
        char temp[SIZE];
        getcwd(temp,SIZE);
        snprintf(pwd,SIZE,"PWD=%s",temp);//以PWD=%s的格式，将temp打印到pwd里，长度位SIZE
        putenv(pwd);//把当前路径导到环境变量，这样就可以实时更改当前路径
    }

    else if(strcmp("export",argv[0]) == 0)
    {
        ret = 1;
        if(argv[1])
        {
            strcpy(env,argv[1]);
            putenv(env);
        }
    }

    else if(strcmp("echo",argv[0]) == 0)
    {
        ret = 1;
        if(!argv[1]) printf("\n");
        else{
            if(argv[1][0] == '$')
            {
                if(argv[1][1] == '?')
                {
                    printf("%d\n",lastcode);
                    lastcode = 0;
                }
                else {
                    char* e = getenv(argv[1]+1);
                    printf("%s\n",e);
                }
            }
            else{
                printf("%s\n",argv[1]);
            }
        }
    }
    return ret;
    //2.执行
}


int main()
{   
    while(1)
    {
        //1.打印命令行提示符，获取用户输入命令字符串
        char commandline[SIZE];

        int n = Internative(commandline,SIZE);  
        if(n == 0) continue;
        //2.对命令字符串进行切割
        Split(commandline);

        //3.处理内建命令
        n = BuildinCmd();
        if(n) continue;
    
        Execute();
        //4.执行这个命令
        //    for(int i=0;argv[i];i++)
        //    {
        //        printf("argv[%d]:%s\n",i,argv[i]);
        //    }

    }
    return 0;
}

